package listbyorder.access001_100.test98;

import listbyorder.utils.TreeNode;

/**
 * @author code_yc
 * @version 1.0
 * @date 2020/6/6 10:33
 */
public class Solution2 {

    // 使用Morris遍历来求解
    public boolean isValidBST(TreeNode root) {
        Integer pre = null;
        if (root != null) {
            TreeNode c1 = root;
            TreeNode c2 = null;
            while (c1 != null) {
                c2 = c1.left;
                if (c2 != null) {
                    while (c2.right != null && c2.right != c1) {
                        c2 = c2.right;
                    }
                    if (c2.right == null) {
                        c2.right = c1;
                        c1 = c1.left;
                        continue;
                    }
                    if (c2.right == c1) {
                        c2.right = null;
                    }
                }
                if (pre != null && c1.val <= pre) {
                    return false;
                }
                pre = c1.val;
                c1 = c1.right;
            }
        }
        return true;
    }
}
